import { _decorator, Component, Mask, Node, Sprite, tween, UIOpacity } from 'cc';
import bezier_line from 'db://assets/bezier/bezier_line';
import { FishMgr } from './FishMgr';
import { CannonControl } from './CannonControl';
import { gameMgr } from '../../gameMgr';
const { ccclass, property } = _decorator;

@ccclass('FishItem')
export class FishItem extends Component {
    //此代码动态添加，预制体并未挂载

    line:bezier_line = null;

    life_val:number = 3;

    runSpeed = 50;

    uio:UIOpacity = null;

    life_mask:Mask = null;
    life_spr:Sprite = null;

    mask_alphaThreshold = 0;

    stopRun = false;

    /** 此鱼产生多少金币 */
    generate_coin = 1

    onLoad(){
        this.uio = this.node.addComponent(UIOpacity);
       
        this.life_mask = this.node.getChildByName("mask").getComponent(Mask)
        this.life_spr = this.life_mask.node.getChildByName("life").getComponent(Sprite)

    }



    setLine(_line:bezier_line){
        this.line = _line;
        this.mask_alphaThreshold = 0;
        this.life_mask.alphaThreshold = 0;
        this.life_spr.spriteFrame = null;
    }
    
    /**
     * 减少鱼的生命值
     * @param val 默认减1滴血
     */
    subLife_val(val:number = 1 ){
        this.life_val -= val;

    }

    /** 判断死亡 执行动画 */
    judge_anim(indexSpr:number){
        
        this.life_spr.spriteFrame = FishMgr.Inst.fish_life_Imgs[indexSpr]

        this.mask_alphaThreshold += 0.34;

        tween(this.life_mask).to(0.3 , {alphaThreshold : this.mask_alphaThreshold}).start()

        if (this.life_val == 0) {
            this.life_val = 0;
            if (this.mask_alphaThreshold >= 1) {
                this.deathAnim();
            }
        }
    }

    /** 死亡动画 */
    deathAnim(isRestart = true){
        this.line.stopRun();
        console.log("死亡动画")
        const _anim_time = 0.3;
        tween(this.uio)
            .to(_anim_time , {opacity : 80})
            .to(_anim_time , {opacity : 255})
            .to(_anim_time , {opacity : 80})
            .to(_anim_time , {opacity : 255})
            .to(_anim_time , {opacity : 0})
            .call(()=>{
                if(isRestart)
                    this.restartRun();
            })
            .start();

        this.stopRun = !isRestart

        // this.scheduleOnce(()=>{
        //     this.restartRun();
        // } , 0.3 * 5 + 1)
    }

    /** 重新开始游 */
    async restartRun(){

        if(this.stopRun)return;

        this.life_val = 3;
        
        FishMgr.Inst.removeLine(this.line);

        await FishMgr.Inst.runRestart(this.runSpeed , this.node);
        this.scheduleOnce(()=>{
            this.uio.opacity = 255;
        } , 1.5)
    }
}


